<?php


namespace app\api\tools;


use think\Exception;
use think\Db;
use think\Cache;
use app\api\controller\Cash;

class ToolsClass
{
    public static function curl($url, $params = false, $ispost = 0, $https = 0)
    {
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8'
            )
        );
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        }
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                if (is_array($params)) {
                    $params = http_build_query($params);
                }
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }
    public static function SendMsg($data,$access_token){
        $MsgUrl="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$access_token; //微信官方接口，需要拼接access_token
        return json_decode(self::curl($MsgUrl,$params=json_encode($data),$ispost=1,$https=1)); //访问接口，返回参数
    }
    //获取access_token
    public static function access_token(){
        $appid = constant('APP_ID');   //小程序appid
        $secret = constant('APP_SECRET'); //小程序secret
        $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=". $appid."&secret=".$secret; //微信给出的获取access_token的接口


        $headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
        $output = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl);
        $access_token=json_decode($output)->{"access_token"};  //访问接口获取access_token
        return $access_token;
    }

    //构造请求
    public static function httpWurl($url, $params, $method = 'GET', $header = array(), $multi = false){
        date_default_timezone_set('PRC');
        $opts = array(
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER     => $header,
            CURLOPT_COOKIESESSION  => true,
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_COOKIE         =>session_name().'='.session_id(),
        );
        /* 根据请求类型设置特定参数 */
        switch(strtoupper($method)){
            case 'GET':
                // $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                // 链接后拼接参数  &  非？
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                break;
            case 'POST':
                //判断是否传输文件
                $params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                return ['errcode'=>'4041','errmsg'=>'不支持的请求方式'];
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data  = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if($error) return ['errcode'=>'4042','errmsg'=>'请求发生错误：'.$error];
        return  $data;
    }

    //检查数据真伪
    public static function checkEncryptedData($appid,$openid,$session_key,$iv,$encryptedData){

        if (strlen($session_key) != 24) {
            return 4044;
        }
        $aesKey=base64_decode($session_key);

        if (strlen($iv) != 24) {
            return 4045;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);
        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj=json_decode( $result );
        if( $dataObj  == NULL || $dataObj->watermark->appid != $appid||$dataObj->openId!=$openid)
        {
            return 4046;
        }
        return $dataObj;
    }

    //添加浏览记录
    public static function addUserBrowseRecords($userId,$watchType,$watchId,$resource,$last_user_id=''){
        $time = time();
        $map['user_id'] = array('eq',$userId);
        $map['watch_type'] = array('eq',$watchType);
        $map['watch_id'] = array('eq',$watchId);
        //需要区分来源 浏览一次记录一次
        $map['resource'] = array('eq',$resource);
        try {
//            $result = Db::name('user_foot_print')
//                ->where($map)
//                ->field('visits_number')
//                ->select();
//            if(is_array($result)&&count($result)>0){
//                $result = Db::name('user_foot_print')
//                    ->where($map)
//                    ->update(['createtime'=>$time,'visits_number'=>$result[0]['visits_number']+1]);
//            }else{
                $info = [
                    'user_id'=>$userId,
                    'watch_type'=>$watchType,
                    'watch_id'=>$watchId,
                    'resource'=>$resource,
                    'last_user_id'=>$last_user_id,
                    'createtime'=>$time
                ];
                $result = Db::name('user_foot_print')
                    ->where($map)
                    ->insert($info);
//            }
        }catch (Exception $e){
            $result =  $e->getMessage();
        }
        return $result;

    }

    //获得商品列表
    public static function getGoodsList($userId,$classifyId,$page,$num){

        if($classifyId != -1)$map['goods_cate_id'] = array('eq',$classifyId);

        $map['user_id'] = array('eq',$userId);
        $map['is_delete'] = array('eq',0);
        try {
            $result = Db::name('goods')
                ->where($map)
                ->order('id desc')
                ->field(['id', 'goods_cate_id', 'name','image_id', 'specification', 'price', 'describe', 'promise'])
                ->paginate($num)
                ->toArray();
            if(!is_array($result))
                throw new Exception('查询商品表出错');
        }catch (Exception $e){
            $result = $e->getMessage();
        }finally{
            return $result;
        }

    }
    //退款流程
    public static function refundForOrder($activity_id,$user_id,$certify_id){
        try{
            Db::startTrans();
            //支付这块现在先暂时写死。
            if (!$activity_id || !$certify_id){
                return 2;//("操作失败",'');
            }

            $connectCertify = Db::name("dragon_list")->where('certify_id',$certify_id)->find();

            //统计退款金额
            $whe =[];
            $whe['user_id'] = $user_id;
            $whe['activity_id'] = $activity_id;
            $whe['order_no'] = $connectCertify['order_no'];//凭证的订单号跟cash_list是一个号
            $whe['type'] = array("between","3,4");
            $money = Db::name("cash_list")->where($whe)->sum('money');
            //用户表账户余额需要在增加
            $res = Db::name("user")->where("id",$user_id)->value("money");
            $data =[];
            $data['money'] = $res + $money;
            $res = Db::name("user")->where("id",$user_id)->update($data);
            if ($res){
                //流水订单表需要同步记录 需要区分 下单和手续费
                $cashListData = [];
                $cashListData['user_id'] = $user_id;
                $cashListData['status'] = 2;
                $cashListData['createtime'] = time();
                $cashListData['activity_id'] = $activity_id;
                $cashListData['money_account'] = $res;//当前账户余额(此时金额目前为  下单金额+手续费 )

                $cashListData['type'] = 5;//支付订单
                $cashListData['mark'] = '接龙退款';//这里包括服务费以及下单金额
                $cashListData['money'] = $money;//下单金额
                $order_no_4 = ToolsClass::orderRule(4);//1 凭证 2接龙表 3 提现 4 退款  5充值
                $cashListData['order_no'] = $order_no_4;
                Db::name("cash_list")->insert($cashListData);
                //更新凭证表 接龙表
                Db::name('connect_certify')->where('id',$certify_id)->update(array('status'=>3));
                Db::name('dragon_list')->where('id',$connectCertify['id'])->update(array('status'=>3));
            }

            Db::commit();
            return 1;//("退款成功",'');
        }catch (Exception $e){
            Db::rollback();

            return 2;//$this->error("退款失败",'');
        }
    }
    //用商品分类ID查分类名
    public static function getClassifyName($classifyId){
        if($classifyId == 0) return ['classify_name'=>'未分类'];
        $map['id'] = array('eq',$classifyId);
        try{
            $result = Db::name('goods_cate')
                ->where($map)
                ->field('classify_name')
                ->select();
            $result = is_array($result)&&count($result)>0?$result[0]:['classify_name'=>'未知分类'];

        }catch (Exception $e){
            $result = $e->getMessage();
        }
        return $result;
    }

    //用图片id字符串获取图片地址
    public static function getImageByImageIdStr($imageIdStr,$userId=''){
        $strArr = explode(',',$imageIdStr);
        $arr = [];
        for ($i = 0;$i<count($strArr);$i++){
            $item = (int)$strArr[$i];
            if($item!=0)
                array_push($arr,$item);
        }
        if (count($arr)>0) {
            $map['id'] = array('in', $arr);
//            $map['user_id'] = array('eq', $userId);
            try {
                $result = Db::name('attachment')
                    ->where($map)
                    ->field('url')
                    ->select();
                $arr = [];
                foreach ($result as $item){
                    array_push($arr,$item['url']);
                }
                $result = $arr;
            } catch (Exception $e) {
                $result = $e->getMessage();
            }
            return $result;
        }else{
            return [];
        }
    }

    //通过用户ID获取其所创建过的商品分类
    public static function getClassifyInfo($userId){
        $map['user_id'] = $userId;
        try{
            $result = Db::name('goods_cate')
                ->where($map)
                ->field('id,classify_name')
                ->order('id desc')
                ->select();
        }catch (Exception $e){
            $result = $e->getMessage();
        }finally{
            return $result;
        }
    }

    //修改商品信息
    public static function updateGoods($goodsId,$goodsInfo){
        $map['id'] = array('eq',$goodsId);
        try{
            $result = Db::name('goods')
                ->where($map)
                ->update($goodsInfo);
        }catch (Exception $e){
            $result = $e->getMessage();
        }finally{
            return $result;
        }
    }

    //创建商品
    public static function createGoods($goodsInfo){
        try{
            $result = Db::name('goods')
                ->insertGetId($goodsInfo);
        }catch (Exception $e){
            $result = $e->getMessage();
        }finally{
            return $result;
        }
    }

    //删除商品 参数示例[1,2,3],
    public static function delGoods($userId,$goodsIdArr){
        try{
            $map['id'] = array('in',$goodsIdArr);
            $map['user_id'] = array('eq',$userId);
            $result = Db::name('goods')
                ->where($map)
                ->update(['is_delete'=>1]);
        }catch (Exception $e){
            $result = 0;
        }
        return $result;
    }

    public static function checkGoodsClassifyIsOnly($userId,$typeName){
        $map['user_id'] = array('eq',$userId);
        $map['classify_name'] = array('eq',$typeName);
        try{
            $result = Db::name('goods_cate')
                ->where($map)
                ->find();
            $result = $result?true:false;
        }catch (Exception $e){
            $result = false;
        }finally{
            return $result;
        }
    }

    //修改商品分类信息
    public static function updateGoodsClassify($classifyId,$userId,$typeName){
        $map['id'] = array('eq',$classifyId);
        try{
            $result = Db::name('goods_cate')
                ->where($map)
                ->update(['user_id'=>$userId,'classify_name'=>$typeName]);
        }catch (Exception $e){
            $result = $e->getMessage();
        }finally{
            return $result;
        }
    }

    //创建商品分类
    public static function createGoodsClassify($userId,$typeName){
        try{
            $result = Db::name('goods_cate')
                ->insertGetId(['user_id'=>$userId,'classify_name'=>$typeName]);
        }catch (Exception $e){
            $result = $e->getMessage();
        }finally{
            return $result;
        }
    }

    //删除商品分类
    public static function delGoodsClassify($userId,$goodsTypeId){
        $result = 1;
        try{
            Db::startTrans();
            $map['goods_cate_id'] = array('eq',$goodsTypeId);
            $map['user_id'] = array('eq',$userId);
            Db::name('goods')
                ->where($map)
                ->update(['goods_cate_id'=>0]);

            Db::name('goods_cate')
                ->delete($goodsTypeId);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $result = $e->getMessage();
        }
        return $result;
    }

    //搜索商品列表
    public static function searchGoods($userId,$classifyId,$keyword,$page,$num){

        $map['user_id'] = array('eq',$userId);
        if($classifyId != 0 && $classifyId != -1)$map['goods_cate_id'] = array('eq',$classifyId);
        $map['name'] = array('like','%'.$keyword.'%');
        $map['is_delete'] = array('eq',0);
        try{
            $result = Db::name('goods')
                ->where($map)
                ->field(['id','goods_cate_id','name','specification','image_id','num','price','describe','promise'])
                ->order('createtime desc')
                ->paginate($num,$page)
                ->toArray();
        }catch (Exception $e){
            $result = $e->getMessage();
        }finally{
            return $result;
        }
    }
    //添加消息配置
//    public static function addSettinConfig($userId){
//        $data = [];
//        $data['user_id'] = $userId;
//        if (!Db::name("setting_config")->where($data)->find()){
//            $data['message_sort'] = 0;
//            $data['open'] = 0;
//            $data['who_message'] = 0;
//            $data['uptime'] = time();
//            Db::name("setting_config")->insert($data);
//        }
//    }
    //判断是否有权限留言 $activity_id 接龙id  $user_id 参与者 这里指的是 完成过接龙的人
    public static function checkMessage($activity_id,$user_id,$type=1){
        //针对留言设置的 查看是否有权限
        $setting_config = Db::name("activity")
            ->where("id",$activity_id)
            ->field("message_sort,who_message,open")
            ->find();
        //$type 1 获取排序方式 2 获取留言权限
        if ($type == 1){
            //0 时间 1点赞数
            return $setting_config['open'];
        }else{
            //是否开启留言
            if($setting_config['open']){
                //留言的人员权限  0 所有人 1 参与者
                if ($setting_config['who_message']){
                    $where =[];
                    $where['activity_id'] = $activity_id;
                    $where['user_id'] = $user_id;
                    if (Db::name("dragon_list")->where($where)->find()){
                        return 1;
                    }
                    return 3; //并非参与者
                }
                return 1;//所有人 可以操作
            }else{
                return 2;//已关闭留言
            }
        }

    }
    //添加粉丝
    public static function addFans($userId,$fansId,$time){
        $map['user_id'] = array('eq',$userId);
        $map['fans_user_id'] = array('eq',$fansId);
        $result = Db::name('fans')
            ->where($map)
            ->find();
        if(!$result){
            $info = [
                'user_id' => $userId,
                'fans_user_id' => $fansId,
                'createtime' => $time,
            ];

            Db::name('fans')->insert($info);
        }
    }

    //获取粉丝表
    public static function fansList($userId,$limit,$page,$type='',$keyword=''){
        $map['f.user_id'] = array('eq',$userId);
        if ($keyword){
            $map['u.nickname'] = array('like',"%".$keyword."%");
        }
        $arr = [];
        $result = Db::name('fans')
            ->alias("f")
            ->join("user u",'f.fans_user_id = u.id')
            ->where($map)
            ->field('f.fans_user_id,u.nickname,u.avatar')
            ->order('f.createtime desc')
//            ->group('f.user_id')
            ->paginate($limit)
            ->toArray();
        foreach ($result['data'] as $item){
            array_push($arr,$item['fans_user_id']);
        }
        if (!$type && $arr){
            $result['data'] = self::getNearestParticipationOrBrowsing($userId,$arr);
        }
        return $result;
    }

    //用用户id数组获取用户最近时间浏览的接龙或参加的活动 参数示例[1,2,3]
    public static function getNearestParticipationOrBrowsing($userId,$userIdArr){
        $result = [];
        try {
            foreach ($userIdArr as $item) {
                $arr = [];
                $resultDL = Db::name('dragon_list dl,wek_activity a')
                    ->where("dl.user_id='$item' AND a.user_id = '$userId' AND dl.activity_id = a.id")
                    ->field('dl.activity_id,dl.user_id,dl.createtime,a.theme')
                    ->order('dl.createtime desc')
                    ->limit(1)
                    ->find();
                $resultUFP = Db::name('user_foot_print ufp,wek_activity a')
                    ->where("ufp.user_id='$item' AND a.user_id = '$userId' AND ufp.watch_id = a.id")
                    ->field('ufp.watch_id,ufp.user_id,ufp.createtime,a.theme')
                    ->order('ufp.createtime desc')
                    ->limit(1)
                    ->find();
                $DL = $resultDL? $resultDL['createtime']:0;
                $UFP = $resultUFP? $resultUFP['createtime']:0;
                if ($DL >= $UFP && $DL > 0){
                    $resultUser = self::getUserAvatarAndNickname($resultDL['user_id']);
                    $resultDL['userInfo'] = is_array($resultUser)&&count($resultUser)>0?$resultUser:['avatar'=>'','nickname'=>''];
                    $resultDL['recentActivities'] = '查看了'. $resultDL['theme'].'接龙';
                    $arr = $resultDL;
                }else if($DL < $UFP && $UFP > 0){
                    $resultUser = self::getUserAvatarAndNickname($resultUFP['user_id']);
                    $resultUFP['userInfo'] = is_array($resultUser)&&count($resultUser)>0?$resultUser:['avatar'=>'','nickname'=>''];
                    $resultUFP['recentActivities'] = '参加了'. $resultUFP['theme'].'接龙';
                    $arr = $resultUFP;
                }

                $arr['time'] = self::getTimeDay($arr['createtime']);
                $arr['historicalData'] = self::getUserHistoricalData($userId,$arr['user_id']);
                $result[] = $arr;
            }

            $len = count($result);
            for($i=1;$i<$len;$i++){
                for($j=$len-1;$j>=$i;$j--){
                    if($result[$j]['createtime']>$result[$j-1]['createtime']){
                        $x=$result[$j];
                        $result[$j]=$result[$j-1];
                        $result[$j-1]=$x;
                    }
                }
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
        return $result;
    }

    //用用户id数组查询用户历史数据统计
    public static function getUserHistoricalData($userId,$fansId){
        try{
            $foot = Db::name('user_foot_print ufp,wek_activity a')
                ->where("ufp.user_id='$fansId'AND a.user_id='$userId' AND watch_id = a.id")
                ->count();
            $dragon = Db::name('dragon_list dl,wek_activity a')
                ->where("dl.user_id='$fansId'AND a.user_id='$userId' AND activity_id = a.id")
                ->count();
            $result['foot'] = $foot;
            $result['dragon'] = $dragon;
            $result['consumption'] = 100.99;//在该用户身上总的交易金额，等待
        }catch (Exception $e){
            $result = $e->getMessage();
        }
        return $result;
    }

    //用户id数组查用户头像和昵称
    public static function getUserAvatarAndNickname($userId){
        try{
            $map['id'] = array('eq',$userId);
            $result = Db::name('user')
                ->where($map)
                ->field(['avatar','nickname'])
                ->select();
        }catch (Exception $e){
            $result = $e->getMessage();
        }
        return $result;
    }
    //地址id数组查提货地址
    public static function getAddress($addressId){
        try{
            $map['id'] = array('eq',$addressId);
            $result = Db::name('delivery_place')
                ->where($map)
                ->field('provice,city,region,detail_address')
                ->select();
        }catch (Exception $e){
            $result = $e->getMessage();
        }
        return $result;
    }
    //接龙活动id数组查接龙活动主题
    public static function getActivityTheme($activityId){
        try{
            $map['id'] = array('eq',$activityId);
            $result = Db::name('activity')
                ->where($map)
                ->field('theme')
                ->select();
        }catch (Exception $e){
            $result = $e->getMessage();
        }
        return $result;
    }

    //输入时间戳获取描述文字
    public static function getTimeDay($time){
        if(is_int($time)&&time()-$time<0) return '时间错误';
        $temp = time()-$time;
        $year = (int)($temp/(12*30*24*3600));
        if($year == 0) {
            $month = (int)($temp / (30 * 24 * 3600));
            if ($month == 0) {
                $day = (int)($temp / (24 * 3600));
                if ($day == 0) {
                    $hour = (int)($temp / (3600));
                    if ($hour == 0) {
                        $minute = (int)($temp / 60);
                        $result = $minute == 0?'1分钟之前':$minute.'分钟之前';
                    } else {
                        $result = $hour . '小时之前';
                    }
                } else {
                    $result = $day . '天之前';
                }
            }else{
                $result = $month.'月之前';
            }
        }else{
            $result = $year.'年之前';
        }

        return $result;
    }
//下单记录凭证以及接龙表
    public static function orderMoreTable($user_id,$money,$activity_id,$liaison_man,$mobile,$address,$buy_content_res,$mark,$buy_number,$resource,$user_name='',$customize=''){
        try{
            Db::startTrans();

            //在操作之前 先判断是否同一个用户可以点击多次

            //在所有步骤之前先判断数量是否已经达到上限
            $buy_content = json_decode($buy_content_res,1);
            $type = Db::name("activity")->where("id",$activity_id)->field('type')->find();
            $table = $type['type'] == 1 ? 'enrollment' : 'activity_goods';
            if ($buy_content){
                foreach ($buy_content as &$value){
                    $where = [];
//                    $where['num'] = array('gt',0);
                    $where['id'] = $value['id'];
                    $num = Db::name($table)->where($where)->field('rest_num,name')->find();
                    if (!$num){
                        return 5;
                    }
                    if ($value['num'] > $num['rest_num']){
                        return  $num['name'].'的库存不足,只剩下'.$num['rest_num'].'个了';//("已超出库存");
                    }
                }
            }
            //写入凭证表
            $certify_id = self::connectCerfityOrder($user_id,$mark,$liaison_man,$mobile,$address,$money,$buy_content_res,$activity_id,$customize);
            //写入接龙表
            $dragon_id = self::jieLongOrder($user_id,$buy_number,$certify_id['certify_id'],$resource,$activity_id,$customize);
            //用户表账户余额
            $res111 = Db::name("user")->where("id",$user_id)->value("money");
            $res = self::payMoneyForOrder($user_id,$money,$activity_id,$certify_id['certify_id'],$dragon_id['dragon_id'],$dragon_id['order_no'],$res111);
            if ($res == 2){
                $res = $res.'|||'.$dragon_id['order_no'].'|||'.$dragon_id['dragon_id'].'|||'.$res111;
                $paptype = 0;
            }else{
                $paptype = 1;
            }
            //更新付款方式
            self::updatePayType($certify_id['certify_id'],$paptype);// 0 微信扣款 1账户扣款
            //备注存在的情况下 需要发送给接龙发起者一个消息
            if ($mark){
                self::addMessage($activity_id,$user_id,$dragon_id['source_user_id'],$mark,1,$certify_id['certify_id'],0);
            }

            if ($res == 1){
                $msg = $user_name.'【用户在线支付成功】';
                self::addOperatorLog($user_id,$msg,$activity_id,$certify_id['certify_id']);
//                //成功减少库存
//                foreach ($buy_content as &$value){
//                    $where = [];
//                    $where['id'] = $value['id'];
//                    Db::name($table)->where($where)->setDec('rest_num',$value['num']);
//                }
            }
            Db::commit();
            return $res;
        }catch (Exception $e){
            Db::rollback();
            return $e->getMessage();
        }

    }

    //添加操作
    public static function addOperatorLog($user_id,$msg,$activity_id,$certify_id){
        $logData = [];
        $logData['user_id'] = $user_id;
        $logData['msg'] = $msg;
        $logData['activity_id'] = $activity_id;
        $logData['certify_id'] = $certify_id;
        $logData['createtime'] = time();
        Db::name("operator_log")->insert($logData);
    }

    //添加留言
    public static function addMessage($activity_id,$user_id,$source_user_id,$mark,$type=1,$certify_id,$parent_id=0){
        //备注存在的情况下 需要发送给接龙发起者一个消息
        $messageData = [];
        $messageData['activity_id'] = $activity_id;
        $messageData['user_id'] = $user_id;
        $messageData['res_user_id'] = $source_user_id;
        $messageData['msg'] = $mark;
        $messageData['type'] = $type;//1 备注
        $messageData['is_read'] = 0;//0未读 1已读
        $messageData['createtime'] = time();
        $messageData['parent_id'] = $parent_id;
        $messageData['certify_id'] = $certify_id;
        Db::name("message")->insert($messageData);
    }
    //订单规则表
    public static function orderRule($type){
        //type 1 凭证 2接龙表 3 提现 4 退款  5充值

        $date = date("YmdHis");
        $table = 'cash_list';
        $str = '';

        switch ($type){
            case 1:
                $str = 'PZ';
                $table = 'connect_certify';
                break;
            case 2:
                $str = 'JL';
                $table = 'dragon_list';
                break;
            case 3:
                $str = 'TX';
                break;
            case 4:
                $str = 'TK';
                break;
            case 5:
                $str = 'CZ';
                break;
            default:;
        }
        //验证是否订单号存在
        $order_no = $str.$date.rand(0,9999999);
        if (Db::name($table)->where('order_no',$order_no)->find()){
            self::orderRule($type);
        }else{
            return $order_no;
        }
    }
    //验证用户是否为接龙创建者
    public static function checkIsUser($user_id1,$user_id2){
        //检测该用户是否为活动发起者
        $where = [];
        if ($user_id1 == $user_id2){
//            $where['dl.user_id'] = $user_id1;//活动发起者
        }else{
            $where['dl.user_id'] = $user_id2;//登录用户
        }
        return $where;
    }
    //管理员或者接龙发起者点击提现审核
    public static function adminOperatorTx($id,$type=1){
        $where = [];
        $where['id'] = $id;
        $where['status'] = 1;//等待
        $where['type'] =$type;//提现
        if (Db::name("cash_list")->where($where)->find()){
            $res = Db::name("cash_list")->where($where)->update(array("status"=>2,'mark'=>"提现","uptime"=>time()));
            if ($res){
                return 1;
            }else{
                return 0;
            }

        }else{
            return 0;
        }

    }

    //下单付款
    private static function payMoneyForOrder($user_id,$money,$activity_id,$certify_id,$dragon_id,$order_no_1,$res){

        try{
            //真实操作微信支付以及银行卡的操作。。。。。。。


            if ($res < $money){
                //账户余额不足，请直接转微信支付
                return 2;
            }else{
                //余额充足，直接删减余额
                $data =[];
                $data['money'] = $res - $money;
                Db::name("user")->where("id",$user_id)->update($data);
                self::cashListLog($user_id,$activity_id,$res,$order_no_1,$money);
                //这里如果支付成功的话  凭证表和接龙表状态需要改成成功
                Db::name("connect_certify")->where("id",$certify_id)->update(array("status"=>2));
                Db::name("dragon_list")->where("id",$dragon_id)->update(array("status"=>0));
            }


            return 1;
        }catch (Exception $e){
            return 4;
        }
    }

    //生成接龙表 凭证表
    public static function connectCerfityOrder($user_id,$mark,$liaison_man,$mobile,$address,$money,$buy_content_res,$activity_id,$customize){
        //凭证表
        $connectCertifyData = [];
        $connectCertifyData['user_id'] = $user_id;
        $connectCertifyData['status'] = 1;//1已参与 2已完成 3 已取消 4支付失败
        $connectCertifyData['mark'] = $mark;
        $connectCertifyData['liaison_man'] = $liaison_man;
        $connectCertifyData['mobile'] = $mobile;
        $connectCertifyData['address'] = $address;
        $connectCertifyData['money'] = $money;
        $connectCertifyData['serial_number'] = 0;//凭证号
        $connectCertifyData['buy_content'] = $buy_content_res;//接龙购买的内容，json格式存储 如{1(物品id),2(价格)}
        $connectCertifyData['createtime'] = time();
        $connectCertifyData['activity_id'] = $activity_id;
        $order_no_1 = ToolsClass::orderRule(1);//1 凭证 2接龙表 3 提现 4 退款  5充值
        $connectCertifyData['order_no'] = $order_no_1;
        $connectCertifyData['customize'] = $customize;

        Db::name("connect_certify")->insert($connectCertifyData);
        $certify_id = Db::name("connect_certify")->getLastInsID();
        $data  = [];
        $data['certify_id'] =$certify_id;
        $data['order_no'] =$order_no_1;
        return $data;
    }
    //生成接龙表 凭证表
    public static function jieLongOrder($user_id,$buy_number,$certify_id,$resource,$activity_id,$customize){
        //接龙表
        $dragonListData = [];
        $dragonListData['user_id'] = $user_id;
        $dragonListData['status'] = 1;//0 正常 1等待 2取消
        $source_user_id = Db::name("activity")->where("id",$activity_id)->value('user_id');
        $dragonListData['last_user_id'] = $source_user_id;//接龙发起者id
        $dragonListData['num'] = $buy_number;
        $dragonListData['certify_id'] = $certify_id;//凭证id
        $dragonListData['resource'] = $resource;
        $sort_index = Db::name("dragon_list")->where("activity_id",$activity_id)->order('sort_index desc')->field('sort_index')->find();
        $dragonListData['sort_index'] = $sort_index['sort_index'] + 1;//接龙序号
        $dragonListData['createtime'] = time();
        $dragonListData['activity_id'] = $activity_id;
        $dragonListData['customize'] = $customize;

        $order_no_2 = ToolsClass::orderRule(2);//1 凭证 2接龙表 3 提现 4 退款  5充值
        $dragonListData['order_no'] = $order_no_2;
        Db::name("dragon_list")->insert($dragonListData);
        $resource = Db::name("dragon_list")->getLastInsID();
        $data  = [];
        $data['dragon_id'] = $resource;
        $data['order_no'] =$order_no_2;
        $data['source_user_id'] =$source_user_id;
        return $data;
    }
    //生成流水订单表
    public static function cashListLog($user_id,$activity_id,$res,$order_no_1,$money){
        //流水订单表需要同步记录 需要区分 下单和手续费
        $cashListData = [];
        $cashListData['user_id'] = $user_id;
        $cashListData['status'] = 1;
        $cashListData['createtime'] = time();
        $cashListData['activity_id'] = $activity_id;
        $cashListData['money_account'] = $res;//当前账户余额(此时金额目前为  下单金额+手续费 )
        $cashListData['order_no'] = $order_no_1;//下单之后的订单号 = 凭证列表中的订单号  仅仅对于接龙的2条数据

        for ($i=0;$i<2;$i++){
            if ($i == 1){
                $cashListData['type'] = 3;//支付订单
                $cashListData['mark'] = '支付订单';
                $cashListData['money'] = $money * 0.99;//下单金额
            }else{
                $cashListData['type'] = 4;//支付服务费
                $cashListData['mark'] = '支付服务费';
                $cashListData['money'] = $money * 0.01;//下单金额
            }
            Db::name("cash_list")->insert($cashListData);
        }
    }
    //获取用户的openid
    public static function getUserOpenId($userid){
        $openid = Db::name('user')->where('id',$userid)->value('open_id');
        return $openid;
    }


    //更新登录时间
    public static function updateUserLoginTime($id){
        Db::name("user")->where("id",$id)->update(array("logintime"=>time()));
    }

    //统计浏览人数
    public static function countNum($type,$id){
        //统计浏览的人数  活动表有冗余这个统计字段，暂时先不用
        $userFootPrintCountWhere = [];
        $userFootPrintCountWhere['watch_type'] = $type;
        $userFootPrintCountWhere['watch_id'] = $id;
        $userFootPrintCount = Db::name('user_foot_print')->where($userFootPrintCountWhere)->count();
        return $userFootPrintCount;
    }
    public static function getTableName($type){
        $table = '';
        if ($type == 1){
            $table = 'enrollment';
        }elseif($type == 2){
            $table = 'activity_goods';
        }
        return $table;
    }
    public static function updatePayType($id,$pay_type){
        Db::name("connect_certify")->where('id',$id)->update(array('pay_type'=>$pay_type));
    }
}